package quelle;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * DataSource
 * Sends periodically data via UDP.
 * 
 * @author Jan Quenzel
 * @author Rico Flaegel
 */
public class DataSource implements Runnable{
	/**
	 * receive port of the station
	 */
	private int recport;
	/**
	 * send port of Datagramm/Message
	 */
	private int sendport;
	/**
	 * address of station 
	 */
	private String address = "localhost";
	/**
	 * Socket for the Messages
	 */
	private DatagramSocket sock;
	/**
	 * represent the Message
	 */
	private String message;
	/**
	 * number of source
	 */
	private int nmbr;
	/**
	 * team number, use to identify the mesage
	 */
	private int teamnumber;
	/**
	 * use to increment the number
	 */
	private static AtomicInteger cntNmbr = new AtomicInteger(1);
	
	public DataSource(int sendport, int recport,int tnmbr, String message){
		this.sendport = sendport;
		this.recport = recport;
		this.teamnumber = tnmbr;
		this.nmbr = cntNmbr.getAndIncrement();
		this.message = (message == null) ? getMessage() : message;
	}
	
	/**
	 * generate message string
	 * @return the message
	 */
	public String getMessage(){
		return "team "+this.teamnumber+"-"+this.nmbr;
	}

	/**
	 * starts the DataSource
	 * @param args parameters are the send port, the receive port and the team number
	 */
	public static void main(String[] args) {
		try{
			if(args.length == 3 || args.length == 4){
				int sendport = Integer.parseInt(args[1]);
				int recport = Integer.parseInt(args[2]);
				int tnmbr = Integer.parseInt(args[0]);
				String message = null;
				if(args.length == 4){
					message = args[3];
				}
				DataSource sr = new DataSource(sendport,recport,tnmbr,message);
				ExecutorService exec = Executors.newSingleThreadExecutor();
				exec.execute(sr);
				exec.shutdown();
			}else{
				throw new NumberFormatException();
			}
		}catch(NumberFormatException e){
			System.err.println("Wrong number of Input parameters... Usage: DataSource <teamnumber> <sendport> <recport> [<message>]");
		}
	}

	/**
	 * sends in 1 second intervals messages to the station
	 */
	@Override
	public void run() {
		try {
			sock = new DatagramSocket(sendport);
			byte[] sb = message.getBytes();
			DatagramPacket sdp = new DatagramPacket(sb, sb.length, InetAddress.getByName(address), recport);
			while(true){
				sock.send(sdp);
				TimeUnit.SECONDS.sleep(1);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			sock.close();
		}
	}
}
